﻿using System;
using System.Web.Mvc;

namespace CodeContrib.Web.Mvc
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
	public class ImportModelStateFromTempDataAttribute : ModelStateTransferAttribute
	{
		public override void OnActionExecuted(ActionExecutedContext filterContext)
		{
			var modelState = filterContext.Controller.TempData[_key] as ModelStateDictionary;

			if (modelState != null)
			{
				if (filterContext.Result is ViewResult)
				{
					filterContext.Controller.ViewData.ModelState.Merge(modelState);
				}
				else
				{
					filterContext.Controller.TempData.Remove(_key);
				}
			}

			base.OnActionExecuted(filterContext);
		}
	}
}